/**
 * @author Roger Wu
 * reference:dwz.drag.js, dwz.dialogDrag.js, dwz.resize.js, dwz.taskBar.js
 */
(function($){
	$(document).keyup(function(event){
		if(event.keyCode==27)$.pdialog.close($.pdialog.getCurrent());
	})
	$.pdialog = {
		_op:{height:300, width:500, minH:40, minW:60, total:20, max:false, mask:false, resizable:true, drawable:true, maxable:true,minable:true,closeable:true,flesh:true},
		_current:null,
		_zIndex:42,
		getCurrent:function(){
			return this._current;
		},
		reload:function(url, data, dlgid){
			var dialog = (dlgid && $("body").data(dlgid)) || this._current;
			if (dialog){
				var jDContent = dialog.find(".dialogContent");
				jDContent.loadUrl(url, data, function(){
					jDContent.find("[layoutH]").layoutH(jDContent);
					$(".pageContent", dialog).width($(dialog).width()-14);
					$(":button.close", dialog).click(function(){
						$.pdialog.close(dialog);
						return false;
					});
				});
			}
		},
		_load:function(dialog,url,options){
			var $this=this;
			var jDContent = $(".dialogContent",dialog);
			
			if(options.iframe){
				var jContent=$('<iframe frameborder="0" src="'+url+'" style="width:100%;height:100%;display:none;" />'),jIframe=$(jContent[0]);
				jIframe.load(function(){
					var modalWin=jIframe[0].contentWindow,jModalDoc=$(modalWin.document);
					modalWin.callback=function(msg){$this.close(dialog,msg);};
					jModalDoc.keydown(function(ev){if(ev.which==27){_this.removeModal();return false;}});
					jIframe.show();
					if(options.opened) options.opened(jDContent);
				});
				jContent.appendTo(jDContent);
				
			}else{
				jDContent.loadUrl(url, {}, function(){
					jDContent.find("[layoutH]").layoutH(jDContent);
					$(".pageContent", dialog).width($(dialog).width()-14);
					$("button.close").click(function(){
						$.pdialog.close(dialog);
					});
					if(options.opened) options.opened(jDContent);
					jDContent.find("button.ok").focus();

					var $dom=jDContent.children().eq(0);
					if($dom.attr("loaded")){
						try{
							var $loaded = eval('(' + $dom.attr("loaded") + ')');
							$loaded($dom);
						}catch(e){	}
					}
				});
			}
		},
		//打开一个层
		open:function(url, dlgid, title, options,callback) {
			url=url+(url.indexOf("?")>0?"&":"?")+"t="+(new Date().getTime());
			
			if($.isFunction(options)){
				callback=options;
				options={};
			}
						
			var op = $.extend({},$.pdialog._op, options,{mask:true});
			var dialog = $("body").data(dlgid);
			//重复打开一个层
			if(dialog) {
				$.pdialog._init(dialog, options, function(){
					if(op.flesh || url != $(dialog).data("url")){
						dialog.data("url",url);
						dialog.find(".dialogHeader").find("h1").html(title);
					}
					$.pdialog._load(dialog,url,options);
				});
				
			} else {//打开一个全新的层
				$("body").append(DWZ.frag["dialogFrag"]);
				//dialog = $(">.dialog:last-child", "body");
				dialog = $(">.dialog","body").last();
				dialog.data("id",dlgid);
				dialog.data("url",url);
				if(options.close) dialog.data("close",options.close);
				if(options.param) dialog.data("param",options.param);
				($.fn.bgiframe && dialog.bgiframe());
				
				$(dialog).css("zIndex", ($.pdialog._zIndex+=2));
				$("div.shadow").css("zIndex", $.pdialog._zIndex - 3);
				
				var dialogHeader = dialog.find(".dialogHeader");
				
				$.pdialog._init(dialog, options, function(){
					dialogHeader.find("h1").html(title);
					$.pdialog._load(dialog,url,options);
				});
				
				dialog.click(function(){
					if($.pdialog._current == dialog) return;
					$.pdialog.switchDialog(dialog);
				});
				
				if(op.resizable)
					dialog.jresize();
				if(op.drawable)
				 	dialog.dialogDrag();
				if(op.closeable){
					$("a.close", dialogHeader).show().click(function(event){ 
						$.pdialog.close(dialog);
						return false;
					});
				}else{
					$("a.close", dialogHeader).hide();
				}
				if (op.maxable) {
					$("a.maximize", dialog).show().click(function(event){
						$.pdialog.switchDialog(dialog);
						$.pdialog.maxsize(dialog);
						dialog.jresize("destroy").dialogDrag("destroy");
						return false;
					});
				} else {
					$("a.maximize", dialogHeader).hide();
				}
				$("a.restore", dialogHeader).click(function(event){
					$.pdialog.restore(dialog);
					dialog.jresize().dialogDrag();
					return false;
				});
				if (op.minable) {
					$("a.minimize", dialogHeader).show().click(function(event){
						$.pdialog.minimize(dialog);
						return false;
					});
				} else {
					$("a.minimize", dialogHeader).hide();
				}
				$("a", dialogHeader).mousedown(function(){
					return false;
				});
				dialogHeader.dblclick(function(){
					if($("a.restore",dialogHeader).is(":hidden"))
						$("a.maximize",dialogHeader).trigger("click");
					else
						$("a.restore",dialogHeader).trigger("click");
				});
				if(op.max) {
					$.pdialog.switchDialog(dialog);
					$.pdialog.maxsize(dialog);
					dialog.jresize("destroy").dialogDrag("destroy");
				}
				$("body").data(dlgid, dialog);
				$.pdialog._current = dialog;
				//$.pdialog.attachShadow(dialog);
			}
			
			if(callback) dialog.data(dlgid+"_callback",callback);
			
			if (op.mask) {
				$(dialog).css("zIndex", 1000);
				$("a.minimize",dialogHeader).hide();
				$(dialog).data("mask", true);
				$("#dialogBackground").show();
			}else {
				//add a task to task bar
				if(op.minable)
					$.taskBar.addDialog(dlgid,title);
			}
		},
		/**
		 * 切换当前层
		 * @param {Object} dialog
		 */
		switchDialog:function(dialog) {
			var index = $(dialog).css("zIndex");
			$.pdialog.attachShadow(dialog);
			if($.pdialog._current) {
				var cindex = $($.pdialog._current).css("zIndex");
				$($.pdialog._current).css("zIndex", index);
				$(dialog).css("zIndex", cindex);
				$("div.shadow").css("zIndex", cindex - 1);
				$.pdialog._current = dialog;
			}
			$.taskBar.switchTask(dialog.data("id"));
		},
		/**
		 * 给当前层附上阴隐层
		 * @param {Object} dialog
		 */
		attachShadow:function(dialog) {
			var shadow = $("div.shadow");
			if(shadow.is(":hidden")) shadow.show();
			shadow.css({
				top: parseInt($(dialog)[0].style.top) - 2,
				left: parseInt($(dialog)[0].style.left) - 4,
				height: parseInt($(dialog).height()) + 8,
				width: parseInt($(dialog).width()) + 8,
				zIndex:parseInt($(dialog).css("zIndex")) - 1
			});
			$(".shadow_c", shadow).children().andSelf().each(function(){
				$(this).css("height", $(dialog).outerHeight() - 4);
			});
		},
		_init:function(dialog, options, callback) {
			var op = $.extend({}, this._op, options);
			var w = $(window), dContent = $(".dialogContent",dialog);
			var mW=op.minW, mH=op.minH, wW=w.width(), wH=w.height();
			
			var height = op.height>op.minH?op.height:op.minH;
			var width = op.width>op.minW?op.width:op.minW;
			height=height>wH?wH:height;
			width=width>wW?wW:width;

			var src = options.event ? $(options.event.srcElement||options.event.target) : null;
			var srcOffset = src? src.offset() : null;
			var srcW = src ? src.width(): wW, srcH=src ? src.height() : wH, srcL=srcOffset ? srcOffset.left : 0, srcT=srcOffset ? srcOffset.top : 0;
						
			var nL = wW/2-mW/2, dL = wW/2-width/2, l = src?srcL+srcW/2-mW/2:nL;
			var nT = wH/2-mH/2, dT = wH/2-height/2, t = src?srcT+srcH/2-mH/2:nT;
			
			
			
			dialog.data("position",{
				oL:l,oT:t,
				nL:nL,nT:nT,
				oW:mW,oH:mH
			});
			
			var hH = $(".dialogHeader", dialog).outerHeight(), fH = $(".dialogFooter", dialog).outerHeight();
			
			dialog.height(mH+"px").width(mW+"px");
			
			dialog.css({
				left: l,
				top: t
			});
			
			var loading = $("<div class='loading'></div>");
			loading.appendTo(dContent);
			
			dContent.height(mH - hH - fH - 6);
			$("div.shadow").hide();

			l!=nL?move():zoom();
			
			function move(){
				dialog.animate({
					left:nL,
					top:nT
				},{
					duration:100,
					complete:zoom
				});
			}
			
			function zoom(){
				dialog.animate({
					width:width,
					height:height,
					left:dL,
					top:dT
				},{
					duration:250,
					step:function(){
						dContent.height(dialog.height() - hH - fH - 6);
					},
					complete:function(){
						loading.remove();
						$.pdialog.attachShadow(dialog);
						setTimeout(function(){
							if(callback)callback();
						},1);
					}
				})
			}
		},
		/**
		 * 初始化半透明层
		 * @param {Object} resizable
		 * @param {Object} dialog
		 * @param {Object} target
		 */
		initResize:function(resizable, dialog,target) {
			$("body").css("cursor", target + "-resize");
			resizable.css({
				top: $(dialog).css("top"),
				left: $(dialog).css("left"),
				height:$(dialog).css("height"),
				width:$(dialog).css("width")
			});
			resizable.show();
		},
		/**
		 * 改变阴隐层
		 * @param {Object} target
		 * @param {Object} options
		 */
		repaint:function(target,options){
			var shadow = $("div.shadow");
			if(target != "w" && target != "e") {
				shadow.css("height", shadow.outerHeight() + options.tmove);
				$(".shadow_c", shadow).children().andSelf().each(function(){
					$(this).css("height", $(this).outerHeight() + options.tmove);
				});
			}
			if(target == "n" || target =="nw" || target == "ne") {
				shadow.css("top", options.otop - 2);
			}
			if(options.owidth && (target != "n" || target != "s")) {
				shadow.css("width", options.owidth + 8);
			}
			if(target.indexOf("w") >= 0) {
				shadow.css("left", options.oleft - 4);
			}
		},
		/**
		 * 改变左右拖动层的高度
		 * @param {Object} target
		 * @param {Object} tmove
		 * @param {Object} dialog
		 */
		resizeTool:function(target, tmove, dialog) {
			$("div[class^='resizable']", dialog).filter(function(){
				return $(this).attr("tar") == 'w' || $(this).attr("tar") == 'e';
			}).each(function(){
				$(this).css("height", $(this).outerHeight() + tmove);
			});
		},
		/**
		 * 改变原始层的大小
		 * @param {Object} obj
		 * @param {Object} dialog
		 * @param {Object} target
		 */
		resizeDialog:function(obj, dialog, target) {
			var oleft = parseInt(obj.style.left);
			var otop = parseInt(obj.style.top);
			var height = parseInt(obj.style.height);
			var width = parseInt(obj.style.width);
			if(target == "n" || target == "nw") {
				tmove = parseInt($(dialog).css("top")) - otop;
			} else {
				tmove = height - parseInt($(dialog).css("height"));
			}
			$(dialog).css({left:oleft,width:width,top:otop,height:height});
			$(".dialogContent", dialog).css("width", (width-12) + "px");
			$(".pageContent", dialog).css("width", (width-14) + "px");
			if (target != "w" && target != "e") {
				var content = $(".dialogContent", dialog);
				content.css({height:height - $(".dialogHeader", dialog).outerHeight() - $(".dialogFooter", dialog).outerHeight() - 6});
				content.find("[layoutH]").layoutH(content);
				$.pdialog.resizeTool(target, tmove, dialog);
			}
			$.pdialog.repaint(target, {oleft:oleft,otop: otop,tmove: tmove,owidth:width});
			
			$(window).trigger("resizeGrid");
		},
		close:function(dialog,result) {
			if(typeof dialog == 'string') dialog = $("body").data(dialog);
			var dlgId=dialog.data("id");
			var close = dialog.data("close");
			var go = true;
			if(close && $.isFunction(close)) {
				var param = dialog.data("param");
				if(param && param != ""){
					param = DWZ.jsonEval(param);
					go = close(param);
				} else {
					go = close();
				}
				if(!go) return;
			}	
			var callback=dialog.data(dialog.data("id")+"_callback");
			
			$("div.shadow").hide();
			
			var dContent=$(".dialogContent",dialog);
			var hH = $(".dialogHeader", dialog).outerHeight(), fH = $(".dialogFooter", dialog).outerHeight();
			dContent.children().hide();
			var position = dialog.data("position");
			if(!position){
				remove();
				return;
			}
			function zoom(){
				dialog.animate({
						width:position.oW,
						height:position.oH,
						left:position.nL,
						top:position.nT
					},{
						duration:150,
						step:function(){
							dContent.height(dialog.height() - hH - fH - 6);
						},
						complete:position.nL==position.oL?remove:move
					}
				)
			}
			
			function move(){
				dialog.animate({
						left:position.oL,
						top:position.oT
					},{
						duration:70,
						complete:remove
					}
				)
			}
			
			function remove(){
				$("div.shadow").hide();
				if ($.fn.xheditor) {
					try{
					$("textarea.editor", dialog).xheditor(false);
					}catch(e){}
				}
				$(dialog).unbind("click").hide();
				$("div.dialogContent", dialog).html("");
				if($(dialog).data("mask")){
					$("#dialogBackground").hide();
				} else{
					$.taskBar.closeDialog($(dialog).data("id"));
				}
				
				$("body").removeData(dlgId);
				dialog.remove();
				
				setTimeout(function(){
					if(result!=undefined&&callback) callback(result);
				},1);
			}
			
			zoom();
			
//			if ($.fn.xheditor) {
//				$("textarea.editor", dialog).xheditor(false);
//			}
//			$(dialog).unbind("click").hide();
//			$("div.dialogContent", dialog).html("");
//			$("div.shadow").hide();
//			if($(dialog).data("mask")){
//				$("#dialogBackground").hide();
//			} else{
//				$.taskBar.closeDialog($(dialog).data("id"));
//			}
//			
//			$("body").removeData(dlgId);
//			dialog.remove();
//				
//			if(result!=undefined&&callback) callback(result);
		},
		closeCurrent:function(result){
			this.close($.pdialog._current,result);
		},
		maxsize:function(dialog) {
			$(dialog).data("original",{
				top:$(dialog).css("top"),
				left:$(dialog).css("left"),
				width:$(dialog).css("width"),
				height:$(dialog).css("height")
			});
			$("a.maximize",dialog).hide();
			$("a.restore",dialog).show();
			var iContentW = $(window).width();
			var iContentH = $(window).height();
			$(dialog).css({top:"0px",left:"0px",width:iContentW+"px",height:iContentH+"px"});
			$.pdialog._resizeContent(dialog,iContentW,iContentH);
		},
		restore:function(dialog) {
			var original = $(dialog).data("original");
			var dwidth = parseInt(original.width);
			var dheight = parseInt(original.height);
			$(dialog).css({
				top:original.top,
				left:original.left,
				width:dwidth,
				height:dheight
			});
			$.pdialog._resizeContent(dialog,dwidth,dheight);
			$("a.maximize",dialog).show();
			$("a.restore",dialog).hide();
			$.pdialog.attachShadow(dialog);
		},
		minimize:function(dialog){
			$(dialog).hide();
			$("div.shadow").hide();
			var task = $.taskBar.getTask($(dialog).data("id"));
			$(".resizable").css({
				top: $(dialog).css("top"),
				left: $(dialog).css("left"),
				height:$(dialog).css("height"),
				width:$(dialog).css("width")
			}).show().animate({top:$(window).height()-60,left:task.position().left,width:task.outerWidth(),height:task.outerHeight()},250,function(){
				$(this).hide();
				$.taskBar.inactive($(dialog).data("id"));
			});
		},
		_resizeContent:function(dialog,width,height) {
			var content = $(".dialogContent", dialog);
			content.css({width:(width-12) + "px",height:height - $(".dialogHeader", dialog).outerHeight() - $(".dialogFooter", dialog).outerHeight() - 6});
			content.find("[layoutH]").layoutH(content);
			$(".pageContent", dialog).css("width", (width-14) + "px");
			
			$(window).trigger("resizeGrid");
		}
	};
})(jQuery);